package com.bjf.commqry.util;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.bjf.common.Module;
import com.bjf.common.Rescode;
import com.bjf.commqry.bean.CommonQueryBean;
import com.bjf.commqry.common.CommonQueryConstants;
import com.bjf.exception.BJFException;

public class CommonQueryIncludeParser {

	/** memeber variable: dom4j SAXReader. */
	private SAXReader saxReader;
	public CommonQueryIncludeParser(){
		saxReader = new SAXReader();
	}

	public CommonQueryBean parse(Document document) throws BJFException {
		try {
			CommonQueryBean bean = new CommonQueryBean();
			//parse Data Access Objects
			parseDataAccessObjects(bean,document);
			return bean;
		} catch (BJFException e) {
			throw e;
		} catch (Exception e) {
			BJFException ex = new BJFException();
			ex.initCause(e);
			throw ex;
		}
	}
	
	/**
	 * parse CommonQueryIncludeBean
	 * @param configFile
	 * @return
	 * @throws ComException
	 */
	public CommonQueryBean parse(File configFile)throws BJFException{
		try{
			Document document = saxReader.read(configFile);
			return parse(document);
		}catch(BJFException appEx){
			throw appEx;
		}catch(Exception ex){
			throw new BJFException(Module.SYSTEM_MODULE,
					Rescode.COMMONQUERYINCLUDEPARSER_PARSE_ERROR,
					"parse include file:" + configFile.getName()+" error",ex);
		}
	}

	/**
	 * parse CommonQueryIncludeBean
	 * @param configFile
	 * @return
	 * @throws BJFException
	 */
	public CommonQueryBean parse(InputStream input)throws BJFException{
		try{
			Document document = saxReader.read(input);
			return parse(document);
		}catch(BJFException appEx){
			throw appEx;
		}catch(Exception ex){
			throw new BJFException(Module.SYSTEM_MODULE,
					Rescode.COMMONQUERYINCLUDEPARSER_PARSE_ERROR,
					"parse include file:" +" error",ex);
		}
	}
	
	/**
	 * parse DataAccessObjects
	 * @param bean
	 * @param documemt
	 * @throws BJFException
	 */
	public void parseDataAccessObjects(CommonQueryBean bean,Document document)throws BJFException{
		try{
			List l = document.selectNodes("//" + CommonQueryConstants.COMMON_INCLUDE_ROOT + "/" + CommonQueryConstants.DATAACCESSOBJECTS);
			if(l.size()!=1){
				throw new BJFException(Module.SYSTEM_MODULE,
						Rescode.COMMONQUERYINCLUDEPARSER_PARSE_CONFIGPARAM_PARAM_DAO_ERROR,"parseDataAccessObjects: size error");
			}
			Element daoEle = (Element)l.get(0);
			bean.setDataAccessObjects(daoEle.getTextTrim());
		}catch(BJFException appEx){
			throw appEx;
		}catch(Exception ex){
			throw new BJFException(Module.SYSTEM_MODULE,
					Rescode.COMMONQUERYINCLUDEPARSER_PARSE_DAO_ERROR,
					"parse config file: DataAccessObjects Parameter error",ex);
		}
	}
}
